<template>
  <!-- 面包屑 -->
  <div>
    <el-breadcrumb separator="/">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
      <el-breadcrumb-item>用户列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片 -->
    <el-card>
      <el-row :gutter="20">
        <el-col :span="6">
          <div>
            <el-input v-model="queryInfo.username" placeholder="请输入内容" class="input-with-select" @clear="getUserList"
              clearable>
              <el-button @click="getUserList" slot="append" icon="el-icon-search"></el-button>
            </el-input>
          </div>
        </el-col>
        <el-col :span="6">
          <el-button type="primary" @click="addUserdialogVisible = true">添加用户</el-button>
        </el-col>
      </el-row>
      <template>
        <el-table :data="userListData" style="width: 100%" max-height="250" stripe>
          <el-table-column fixed type="index"></el-table-column>
          <el-table-column fixed prop="username" label="账号" width="150">
          </el-table-column>
          <el-table-column prop="nickname" label="昵称" width="120">
          </el-table-column>
          <el-table-column prop="is_active" label="状态" width="120">
            <template slot-scope="scope">
              <el-switch @change="activeChange(scope.row)" v-model="scope.row.is_active" active-color="#13ce66"
                inactive-color="#ff4949">
              </el-switch>
            </template>
          </el-table-column>
          <el-table-column prop="is_superuser" label="超级管理员" width="120">
            <template slot-scope="scope">
              <el-switch @change="activeChange(scope.row)" v-model="scope.row.is_superuser" active-color="#13ce66"
                inactive-color="#ff4949">
              </el-switch>
            </template>
          </el-table-column>
          <el-table-column fixed="right" label="操作" width="150">
            <template slot-scope="scope">
              <!-- <el-tooltip class="item" effect="dark" content="查看" placement="top" :enterable="false">
                <el-button size="mini" type="warning" icon="el-icon-view" circle></el-button>
              </el-tooltip>
              <el-button size="mini" type="primary" icon="el-icon-edit" circle></el-button> -->
              <template>
                <el-popconfirm title="这是一段内容确定删除吗？" @onConfirm="deleteUser(scope.$index, scope.row.id)">
                  <el-button slot="reference" size="mini" type="danger" icon="el-icon-delete" circle></el-button>
                </el-popconfirm>
              </template>
            </template>
          </el-table-column>
        </el-table>
      </template>
      <!-- 添加用户输入框 -->
      <el-dialog title="添加用户" :visible.sync="addUserdialogVisible" width="30%" @close="handleUserFormClose">
        <!-- from表单区域 -->
        <el-form :model="addUserForm" :rules="addUserFormRules" ref="addUserFormRef" label-width="100px" class="demo-ruleForm">
          <el-form-item label="手机号" prop="mobile">
            <el-input v-model="addUserForm.mobile"></el-input>
          </el-form-item>
          <el-form-item label="姓名" prop="nickname">
            <el-input v-model="addUserForm.nickname"></el-input>
          </el-form-item>
          <el-form-item label="密码" prop="password">
            <el-input type="password" v-model="addUserForm.password"></el-input>
          </el-form-item>
          <el-form-item label="确认密码" prop="rePassword">
            <el-input type="password" v-model="addUserForm.rePassword"></el-input>
          </el-form-item>
        </el-form>
        <!-- 按钮操作区域 -->
        <span slot="footer" class="dialog-footer">
          <el-button @click="resetUserForm">重 置</el-button>
          <el-button type="primary" @click="submitUserForm">确 定</el-button>
        </span>
      </el-dialog>
      <!-- 分页 -->
      <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page="queryInfo.currentPage"
        :page-sizes="[10, 20, 30, 40]" :page-size="queryInfo.pageSize" layout="total, sizes, prev, pager, next, jumper"
        :total="totalPage">
      </el-pagination>
    </el-card>
  </div>
</template>
<script>
  export default {
    data() {
      // 验证
      var validatePass = (rule, value, callback) => {
        if (value === '') {
          callback(new Error('请输入密码'))
        } else {
          if (this.addUserForm.rePassword !== '') {
            this.$refs.addUserFormRef.validateField('rePassword')
          }
          callback()
        }
      }
      var validateRePass = (rule, value, callback) => {
        if (value === '') {
          callback(new Error('请再次输入密码'))
        } else if (value !== this.addUserForm.password) {
          callback(new Error('二次密码不一致！'))
        } else {
          callback()
        }
      }
      var validateMobile = (rule, value, callback) => {
        const regMobile = /^(0|86|17951)?(13[0-9]|15[0123456789]|17[678]|18[0-9]|14[57])[0-9]{8}$/
        if (regMobile.test(value)) {
          callback()
        }
        callback(new Error('请输入合法的手机号'))
      }
      return {
        userListData: [],
        totalPage: 0,
        queryInfo: {
          username: '',
          currentPage: 1,
          pageSize: 10
        },
        // 添加管理员
        addUserdialogVisible: false,
        addUserForm: {
          mobile: '',
          nickname: '',
          password: '',
          rePassword: ''
        },
        addUserFormRules: {
          password: [{
            required: true,
            message: '密码不能为空！',
            trigger: 'blur'
          }, {
            validator: validatePass,
            trigger: 'blur'
          }],
          rePassword: [{
            required: true,
            message: '确认密码不能为空！',
            trigger: 'blur'
          }, {
            validator: validateRePass,
            trigger: 'blur'
          }],
          nickname: [{
            required: true,
            message: '姓名不能为空！',
            trigger: 'blur'
          }],
          mobile: [{
            required: true,
            message: '手机号不能为空！',
            trigger: 'blur'
          }, {
            validator: validateMobile,
            trigger: 'blur'
          }]
        }
      }
    },
    created() {
      this.getUserList()
    },
    methods: {
      async getUserList() {
        // 获取管理员信息
        const {
          data: res
        } = await this.$http.get('account/user/', {
          params: this.queryInfo
        })
        console.log(res)
        this.userListData = res.data.dataList
        this.totalPage = res.data.totalPage
      },
      async updateUserInfo(userInfo) {
        // 更新管理员信息
        const data = await this.$http.put('account/user/' + userInfo.id + '/', userInfo)
        if (data.status === 200 && data.data.status) {
          this.$message.success('修改成功！')
        }
      },
      // 分页事件
      handleSizeChange(newSize) {
        this.queryInfo.pageSize = newSize
        this.queryInfo.currentPage = 1
        this.getUserList()
      },
      // 状态变化事件
      handleCurrentChange(newPage) {
        this.queryInfo.currentPage = newPage
        this.getUserList()
      },
      activeChange(userInfo) {
        this.updateUserInfo(userInfo)
      },
      // 删除用户
      async deleteUser(index, userId) {
        const data = await this.$http.delete('account/user/' + userId + '/')
        if (data.status === 200 && data.data.status) {
          this.$message.success('删除成功！')
          this.userListData.splice(index, 1)
        }
      },
      // 重置表单
      resetUserForm() {
        this.$refs.addUserFormRef.resetFields()
      },
      // 关闭表单
      handleUserFormClose() {
        this.resetUserForm()
        this.addUserdialogVisible = false
      },
      // 提交用户表单
      submitUserForm() {
        // 对整个表单进行验证
        this.$refs.addUserFormRef.validate((valid) => {
          if (valid) {
            // 验证通过，数据提交
            this.$http.post('account/user/', this.addUserForm).then(res => {
              if (res.status === 200 && res.data.status) {
                this.$message.success('创建成功！')
                this.addUserdialogVisible = false
                this.getUserList()
              } else {
                this.$message.error('创建失败！')
              }
            })
          }
        })
      }
    }
  }
</script>
<style>
  .el-pagination {
    text-align: center;
    margin-top: 15px;
  }
</style>
